<template>
  <!-- <h2 class="setting-header">
    <strong>视屏播放测试</strong>
  </h2> -->
  <videoPlay
    ref="videoPlayRef"
    v-bind="videoOptions"
    @ended="endedFun"
    @timeupdate="timeupdateFun"
    @play="handlePlay"
    @pause="handlePause"
    :currentTime="toCurrentTime"
    :src="currentSrc"
  ></videoPlay>
  <div class="bottom">
    <div class="play-status">视频播放中...</div>
    <p>播放进度：{{playbackProgress}}%</p>
  </div>
  <!-- 学中测试弹窗 -->
  <el-dialog 
    v-model="testDialogVisible" 
    width="400px" 
    title="题目测试"
    :before-close="closeTheDialog" 
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="test-dialog">
      <el-form
        ref="formRef"
        :model="form"
        :validate-on-rule-change="false"
        label-width="auto"
        label-position="top"
      >
        <!-- 当前页显示的题目 -->
        <el-form-item
          v-for="question in currentPageQuestions"
          :key="question.id"
          label-position="top"
          v-show="currentPageQuestions.includes(question)"
        >
          <div class="question-content">
            <div class="question-description">
              【<span>{{question.cmp.compName}}</span>】{{question.cmp.label}}
            </div>
            <component
              :is="getComponent(question.cmp.type)"
              v-model:modelValue="question.answer"
              :setting="question.cmp"
            />
          </div>
        </el-form-item>
        
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer"> 
        <el-button  @click="closeTheDialog">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { videoPlay } from 'vue3-video-play'
import 'vue3-video-play/dist/style.css'
import { ref, reactive, markRaw, computed, watch } from "vue";
import { selectByIdPaperQuestion } from "@/api/form";
import { ElMessage } from 'element-plus'
import FormInput from './formItems/FormInput.vue'
import FormTextarea from './formItems/FormTextarea.vue'
import FormRadio from './formItems/FormRadio.vue'
import FormDate from './formItems/FormDate.vue'
import FormCheckbox from './formItems/FormCheckbox.vue'
import FormSelectSingle from './formItems/FormSelectSingle.vue'
import FormSelectMultiple from './formItems/FormSelectMultiple.vue'
import FormFileUpload from './formItems/FormFileUpload.vue'
import FormImgUpload from './formItems/FormImgUpload.vue'

// 组件注册
const components = ref({
  input: markRaw(FormInput),
  textarea: markRaw(FormTextarea),
  radio: markRaw(FormRadio),
  date: markRaw(FormDate),
  checkbox: markRaw(FormCheckbox),
  selectSingle: markRaw(FormSelectSingle),
  selectMultiple: markRaw(FormSelectMultiple),
  fileUpload: markRaw(FormFileUpload),
  imgUpload: markRaw(FormImgUpload)
})

const getComponent = (type) => {
  return components.value[type] || null
}

const props = defineProps({
  videoSrc: {
    type: String,
    default: ''
  },
  currentTime: {
    type: Number,
    default: 0
  },
  testList: {
    type: Array,
    default: () => []
  }
})
const theTestData = ref(props.testList);
console.log("theTestData",theTestData.value);
watch(
  () => props.testList, // 监听的目标
  (newValue) => {
    theTestData.value = newValue; // 更新 theTestData 的值
    console.log('testList 更新了:', newValue);
  },
  { immediate: true, deep: true } 
);
const currentSrc = computed({
  get() {
    console.log("props.videoSrc",props.videoSrc);
    if(props.videoSrc){
      return props.videoSrc
    } else {
      return 'http://10.10.0.120:9000/wave-bucket/videos/2025-05-30/d23abe2a-92eb-4fd8-82b8-d844e2f22350.mp4'
    }
  }
})
const videoPlayRef = ref(null)
const toCurrentTime = computed({
  get() {
    return props.currentTime
  }
})
const playbackProgress = ref(0)
const videoOptions = reactive({
  width: '100%',
  height: '100%',
  color: '#409eff', //主题色
  title: '测试视频播放', //视频名称
  webFullScreen: false, //网页全屏
  speed: true, //进度条拖动
  muted: false, //静音
  autoPlay: true, //自动播放
  loop: false, //循环播放
  mirror: false, //镜像画面
  fluid: true,
  aspectRatio: '16:9',
  control: true, //是否显示控制器
  volume: 0.5, //默认音量0-1
  notSupportedMessage: '此视频暂无法播放，请稍后再试',
  // src: "https://stream7.iqilu.com/10339/upload_transcode/202002/18/20200218114723HDu3hhxqIT.mp4", //视频源
  type: "video/mp4",
  poster: '', //封面
  speedRate: [1.0, 1.25, 1.5, 2.0], // 可选的播放速度
  // qualityLevels: ['720p', '1080p', '320p'],
  controlBtns: [
    'audioTrack', //音轨切换按钮
    'quality', //视频质量切换按钮
    'speedRate', //速率切换按钮
    'volume', //音量
    // 'pip', //画中画按钮
    'fullScreen' //全屏按钮
  ]
})

//根据系统配置更改播放器设置



//计算播放进度
const timeupdateFun = () => {
  let dToolTimeElements = document.getElementsByClassName("d-tool-time")[0];
  var spans = dToolTimeElements.getElementsByTagName('span');
  if (spans.length > 0) {
    var firstSpanContent = timeStringToSeconds(spans[0].textContent);
    var lastSpanContent = timeStringToSeconds(spans[spans.length - 1].textContent);
    //转换两位百分数
    if(lastSpanContent !== 0) {
      playbackProgress.value = Math.round(firstSpanContent / lastSpanContent * 100);
      if(theTestData.value && theTestData.value.length > 0){
        showTest(playbackProgress.value);
      }
    }
  }
}

// 辅助函数：将时间字符串 "HH:MM:SS" 转换为秒数
const timeStringToSeconds = (timeStr) => {
    var parts = timeStr.split(':').map(parseFloat);
    if (parts.length === 3) { // 处理 "HH:MM:SS"
        return parts[0] * 3600 + parts[1] * 60 + parts[2];
    } else if (parts.length === 2) { // 如果是 "MM:SS"
        return parts[0] * 60 + parts[1];
    } else {
        return NaN; // 返回非数字值表示错误
    }
}

const getCurrentTime = () => {
  return Math.floor(document.querySelector('video')?.currentTime) || 0
}

//******学中测试显示
const testDialogVisible = ref(false);
const currentTestQuestion = ref(null);
const currentPageQuestions = ref([]);
const showTest = async (progress) => {
  const triggeredTest = theTestData.value.find(test => 
    progress == test.progress && test.completedTest != true
  );
  // console.log("triggeredTest",triggeredTest);
  
  if (triggeredTest && !testDialogVisible.value && triggeredTest.questionId) {
    try {
      const res = await selectByIdPaperQuestion({id: triggeredTest.questionId});
      if (res.code === 20000) {
        // 2. 设置当前题目
        currentTestQuestion.value = {
          ...res.data,
          formItemId: `test_${triggeredTest.questionId}` // 生成唯一表单ID
        };
        currentTestQuestion.value.answer = null
        // currentTestQuestion.value.answer = "选项一"
        currentPageQuestions.value = [currentTestQuestion.value];
        testDialogVisible.value = true;
        
        // 暂停视频播放
        videoPlayRef.value.pause();
        console.log(`检测到进度 ${progress}，触发题目: ${triggeredTest.questionName}`);
        console.log("题目信息",currentTestQuestion.value);
      }
    } catch (error) {
      console.error('获取题目失败:', error);
    }
  }
}

// 定义可触发的事件
const emit = defineEmits(['play', 'pause', 'end'])
const answerList = ref([])
const closeTheDialog = () => {
  if(currentPageQuestions.value[0] && currentPageQuestions.value[0].answer){
    testDialogVisible.value = false;
    // 找到当前题目并设置 completedTest 为 true
    const currentQuestionId = currentPageQuestions.value[0].id;
    const targetTest = theTestData.value.find(test => test.questionId == currentQuestionId);
    if (targetTest) {
      targetTest.completedTest = true;
    }
    videoPlayRef.value.play();
    answerList.value.push({
      id: currentQuestionId,
      answer: currentPageQuestions.value[0].answer})
  } else {
    ElMessage.warning('请完成答题！')
  }
}

// 绑定原生 video 事件并转发给父组件
function handlePlay() {
  emit('play')
}

function handlePause() {
  console.log("answerList.value",answerList.value);
  emit('pause')
}

//视频播放完毕 当前视频标记观看结束 切换下一条
function endedFun(){
  console.log('播放完毕');
  playbackProgress.value = 100;
  emit('end',answerList.value)
}
// 暴露方法给父组件
defineExpose({
  playbackProgress,
  getCurrentTime,
})
</script>
<style scoped lang="scss">
  #video{
    max-width: 100%;
  }
  .bottom{
    display: flex;
    justify-content: space-between;
    margin-top: px2rem(20);
  }
  .test-dialog{
    .question-description{
      font-size: px2rem(18);
      color: $black;
      margin-bottom: px2rem(10);
    }
  }
</style>
